package gui.tab;

import gui.TuristAssistant;
import gui.dialog.CommChatRoomDialog;
import gui.pop.ChatPopUpMenu;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
import java.util.Map.Entry;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MenuDetectEvent;
import org.eclipse.swt.events.MenuDetectListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;
import org.example.www.communication.ChatService.ChatRoom;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
/**
 * Composite a utilizar como solapa de la aplicacion para interactuar con los
 * servicios de chat.<BR/>
 * internamente se lleva rastro de los chat a los cuales se ah entrado.
 */
public class ChatCompositeTab extends org.eclipse.swt.widgets.Composite {
	
	private java.util.Map<String, CommChatRoomDialog>	enteredChatRooms;
	private java.util.Vector<ChatRoom>					activeChatRooms;
	private ChatPopUpMenu								activChatRoomPopUpMenu;
	
	private Label										swtlblActiveChatRooms;
	private Button										swtbtnRefresh;
	private List										swtlActiveChatRoomsList;
	
	/**
	 * Auto-generated main method to display this
	 * org.eclipse.swt.widgets.Composite inside a new Shell.
	 */
	public static void main(String[] args) {
		showGUI();
	}
	
	/**
	 * Auto-generated method to display this org.eclipse.swt.widgets.Composite
	 * inside a new Shell.
	 */
	public static void showGUI() {
		Display display = Display.getDefault();
		Shell shell = new Shell(display);
		ChatCompositeTab inst = new ChatCompositeTab(shell, SWT.NULL);
		Point size = inst.getSize();
		shell.setLayout(new FillLayout());
		shell.layout();
		if (size.x == 0 && size.y == 0) {
			inst.pack();
			shell.pack();
		} else {
			Rectangle shellBounds = shell.computeTrim(0, 0, size.x, size.y);
			shell.setSize(shellBounds.width, shellBounds.height);
		}
		shell.open();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
	}
	/**
	 * Constructor basado en el constructor super. 
	 */
	public ChatCompositeTab(org.eclipse.swt.widgets.Composite parent, int style) {
		super(parent, style);
		initGUI();
	}
	
	private void initGUI() {
		try {
			this.setLayout(new FormLayout());
			{
				swtbtnRefresh = new Button(this, SWT.PUSH | SWT.CENTER);
				FormData swtbtnRefreshLData = new FormData();
				swtbtnRefreshLData.width = 66;
				swtbtnRefreshLData.height = 23;
				swtbtnRefreshLData.left = new FormAttachment(804, 1000, 0);
				swtbtnRefreshLData.top = new FormAttachment(0, 1000, 8);
				swtbtnRefreshLData.right = new FormAttachment(970, 1000, 0);
				swtbtnRefresh.setLayoutData(swtbtnRefreshLData);
				swtbtnRefresh.setText("Refresh");
				swtbtnRefresh.addMouseListener(new MouseAdapter() {
					@Override
					public void mouseUp(MouseEvent evt) {
						swtbtnRefreshMouseUp(evt);
					}
				});
				swtbtnRefresh
						.setImage(new Image(Display.getCurrent(),
								"resource/tango-icon-theme-0.8.90/16x16/actions/view-refresh.png"));
			}
			{
				swtlblActiveChatRooms = new Label(this, SWT.NONE);
				FormData swtlblActiveChatRoomsLData = new FormData();
				swtlblActiveChatRoomsLData.width = 95;
				swtlblActiveChatRoomsLData.height = 13;
				swtlblActiveChatRoomsLData.left = new FormAttachment(0, 1000,
						12);
				swtlblActiveChatRoomsLData.top = new FormAttachment(0, 1000, 8);
				swtlblActiveChatRooms.setLayoutData(swtlblActiveChatRoomsLData);
				swtlblActiveChatRooms.setText("Active Chat Rooms:");
			}
			{
				FormData swtlActiveChatRoomsListLData = new FormData();
				swtlActiveChatRoomsListLData.width = 347;
				swtlActiveChatRoomsListLData.height = 163;
				swtlActiveChatRoomsListLData.left = new FormAttachment(0, 1000,
						16);
				swtlActiveChatRoomsListLData.top = new FormAttachment(0, 1000,
						38);
				swtlActiveChatRoomsListLData.right = new FormAttachment(976,
						1000, 0);
				swtlActiveChatRoomsListLData.bottom = new FormAttachment(950,
						1000, 0);
				swtlActiveChatRoomsList = new List(this, SWT.H_SCROLL
						| SWT.V_SCROLL | SWT.BORDER);
				swtlActiveChatRoomsList
						.setLayoutData(swtlActiveChatRoomsListLData);
				swtlActiveChatRoomsList
						.addMenuDetectListener(new MenuDetectListener() {
							public void menuDetected(MenuDetectEvent evt) {
								swtlActiveChatRoomsListMenuDetected(evt);
							}
						});
			}
			
			{
				Display.getCurrent().timerExec(500,
						new RecivePendingMsgsTimedTask());
			}
			{
				activChatRoomPopUpMenu = new ChatPopUpMenu(getShell(),
						SWT.POP_UP);
				activChatRoomPopUpMenu.setBoss(swtlActiveChatRoomsList);
				activChatRoomPopUpMenu.setFather(this);
			}
			{
				enteredChatRooms = new Hashtable<String, CommChatRoomDialog>();
				activeChatRooms = new Vector<ChatRoom>();
			}
			this.layout();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Tarea a jecutarse periodicamente para solicitar los mensajes pendientes
	 * de las salas de chat y actualizar las ventanas asociadas a las mismas.
	 */
	private class RecivePendingMsgsTimedTask implements Runnable {
		@Override
		public void run() {
			try {
				java.util.Map<String, java.util.List<String>> msgsByChatRoom = null;
				if (TuristAssistant.chatClient != null) {
					msgsByChatRoom = TuristAssistant.chatClient
							.recivePendingMsgsPerChatRoom();
				}
				if (msgsByChatRoom != null && !msgsByChatRoom.isEmpty()) {
					for (Entry<String, java.util.List<String>> msgs : msgsByChatRoom
							.entrySet()) {
						CommChatRoomDialog crd = enteredChatRooms.get(msgs
								.getKey());
						for (Iterator<String> itMsgs = msgs.getValue()
								.iterator(); crd != null
								&& !crd.getParent().isDisposed()
								&& itMsgs.hasNext();) {
							crd.addMsg(itMsgs.next());
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			Display.getCurrent().timerExec(500,
					new RecivePendingMsgsTimedTask());
		}
	}
	
	/**
	 * Cada vez q se ciere una ventana de chat, se actulizara el mapeo interno.
	 */
	public void chatRoomCompDisposed(CommChatRoomDialog crd) {
		this.enteredChatRooms.remove(crd.getChatRoom().getChatRoomID());
		TuristAssistant.chatClient.quitChatRoom(crd.getChatRoom()
				.getChatRoomID());
	}
	
	/**
	 * Cada vez q se abre una ventana de chat, se actulizara el mapeo interno.
	 */
	public void addEnteredChatRoom(CommChatRoomDialog crc) {
		enteredChatRooms.put(crc.getChatRoom().getChatRoomID(), crc);
		try {
			TuristAssistant.chatClient.enterChatRoom(crc.getChatRoom()
					.getChatRoomID());
		} catch (RuntimeException e) {
			// ya estaba loueado a la sala de chat.
		}
	}
	
	public void swtbtnRefreshMouseUp(MouseEvent evt) {
		activeChatRooms = new Vector<ChatRoom>(TuristAssistant.chatClient
				.getActiveChatRooms());
		this.swtlActiveChatRoomsList.removeAll();
		for (ChatRoom cRoom : activeChatRooms) {
			this.swtlActiveChatRoomsList.add(cRoom.getChatRoomID());
		}
	}
	
	private void swtlActiveChatRoomsListMenuDetected(MenuDetectEvent evt) {
		swtlActiveChatRoomsList.getMenu().setEnabled(false);
		if (this.swtlActiveChatRoomsList.getSelectionIndex() >= 0) {
			ChatRoom cRoom = activeChatRooms.get(this.swtlActiveChatRoomsList
					.getSelectionIndex());
			if (!enteredChatRooms.containsKey(cRoom.getChatRoomID())) {
				this.activChatRoomPopUpMenu.setChatRoom(cRoom);
				swtlActiveChatRoomsList.getMenu().setEnabled(true);
			} else {
				enteredChatRooms.get(cRoom.getChatRoomID()).getParent()
						.setFocus();
			}
		}
	}
	
}
